package com.stud.seckill.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stud.seckill.common.config.CacheService;
import com.stud.seckill.common.enums.CacheKeyEnum;
import com.stud.seckill.mapper.OrderMapper;
import com.stud.seckill.entity.GoodsEntity;
import com.stud.seckill.entity.OrderEntity;
import com.stud.seckill.entity.SeckillGoodsEntity;
import com.stud.seckill.service.GoodsService;
import com.stud.seckill.service.OrderService;
import com.stud.seckill.service.SeckillGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Libra
 * @since 2024-03-30
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {

    @Autowired
    public SeckillGoodsService seckillGoodsService;
    @Autowired
    public GoodsService goodsService;
    @Autowired
    public CacheService cacheService;

    @Override
    public OrderEntity get(Long orderId) {
        OrderEntity order = (OrderEntity) cacheService.get(CacheKeyEnum.订单, orderId);
        if (order == null) {
            order = this.getBaseMapper().selectById(orderId);
            cacheService.set(CacheKeyEnum.订单, orderId, order);
        }
        return order;
    }

    @Transactional
    @Override
    public OrderEntity saveOrder(Long userId, Long goodsId) {

        // 活动商品
        SeckillGoodsEntity seckillGoods = seckillGoodsService.get(goodsId);
        // 商品信息
        GoodsEntity goods = goodsService.get(goodsId);

        // 扣减库存
        goodsService.subStock(goodsId, 1);

        // 生成订单
        OrderEntity order = new OrderEntity();
        order.setUserId(userId);
        order.setGoodsId(goodsId);
        order.setDeliveryAddrId(null);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        this.getBaseMapper().insert(order);

        return order;
    }

    @Override
    public void initOrder() {
        this.remove(Wrappers.lambdaQuery());
    }

}
